package com.zxy.supplier_system.server.utils

import org.apache.poi.ss.usermodel.*
import org.apache.poi.xssf.usermodel.XSSFWorkbook
import org.springframework.core.io.InputStreamResource
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.math.BigDecimal
import java.util.*
import java.util.regex.Matcher
import java.util.regex.Pattern

val Cell.displayCellString: String?
    get() {
        return when (this.cellType) {
            CellType.NUMERIC -> {
                BigDecimal(this.numericCellValue).toPlainString()
            }

            CellType.STRING -> {
                this.stringCellValue
            }

            CellType.BLANK -> {
                null
            }

            else -> {
                null
            }
        }
    }

fun Row.setCellValues(values: Array<out Any?>) {
    values.forEachIndexed { index, any ->
        if (any != null) {
            val cell = this.getCell(index, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK)
            cell.setCellValue(any)
        }
    }
}

fun Row.setCellValues(values: List<out Any?>) {
    this.setCellValues(values.toTypedArray())
}

fun Cell.setCellValue(value: Any) {
    when (value) {
        is String -> {
            this.setCellValue(value)
        }

        is Int -> {
            this.setCellValue(value.toDouble())
        }

        is Double -> {
            this.setCellValue(value)
        }

        is Float -> {
            this.setCellValue(value.toDouble())
        }

        is Long -> {
            this.setCellValue(value.toDouble())
        }

        is Date -> {
            this.setCellValue(value)
        }

        is RichTextString -> {
            this.setCellValue(value)
        }

        is Calendar -> {
            this.setCellValue(value)
        }

        is BigDecimal -> {
            this.setCellValue(value.toDouble())
        }

        is Enum<*> -> {
            this.setCellValue(value.name)
        }

        else -> {
            error("不支持的类型: ${value.javaClass}")
        }
    }
}

fun workbookToInputStreamResource(workbook: XSSFWorkbook): InputStreamResource {
    val out = ByteArrayOutputStream()
    workbook.write(out)
    return InputStreamResource(ByteArrayInputStream(out.toByteArray()))
}

/**
 * 自动调整列表宽度适应中文字符串
 * @param sheet
 * @param size  要调整的列表数量
 */
fun autoColumnWidthForChineseChar(sheet: Sheet, size: Int) {
    for (columnNum in 0 until size) {
        /** 调整每一列宽度  */
        sheet.autoSizeColumn(columnNum)
        /** 获取列宽  */
        val columnWidth: Int = sheet.getColumnWidth(columnNum)
        if (columnNum >= 256 * 256) {
            /** 列宽已经超过最大列宽则放弃当前列遍历  */
            continue
        }
        /** 新的列宽  */
        var newWidth = columnWidth
        /** 遍历所有的行,查找有汉字的列计算新的最大列宽  */
        for (rowNum in 0..sheet.lastRowNum) {
            var currentRow: Row
            if (sheet.getRow(rowNum) == null) {
                continue
            } else {
                currentRow = sheet.getRow(rowNum)
            }
            if (currentRow.getCell(columnNum) != null) {
                val currentCell = currentRow.getCell(columnNum)
                if (currentCell.cellType == CellType.STRING) {
                    val value = currentCell.stringCellValue

                    /** 计算字符串中中文字符的数量  */
                    val count = chineseCharCountOf(value)

                    /**在该列字符长度的基础上加上汉字个数计算列宽  */
                    val length = value.length * 256 + count * 256 * 2
                    /** 使用字符串的字节长度计算列宽  */
//	                    int length = value.getBytes().length*256;
                    if (newWidth < length && length < 256 * 256) {
                        newWidth = length
                    }
                }
            }
        }
        sheet.setColumnWidth(columnNum, newWidth + 256)
    }
}

/**
 * 计算字符串中中文字符的数量
 * 参见 <a hrft="https://www.cnblogs.com/straybirds/p/6392306.html">《汉字unicode编码范围》</a>
 * @param input
 * @return
 */
private fun chineseCharCountOf(input: String?): Int {
    var count = 0 //汉字数量
    if (null != input) {
        val regEx = "[\\u4e00-\\u9fa5]"
        val p: Pattern = Pattern.compile(regEx)
        val m: Matcher = p.matcher(input)
        val len: Int = m.groupCount()
        //获取汉字个数
        while (m.find()) {
            for (i in 0..len) {
                count = count + 1
            }
        }
    }
    return count
}
